package com.community.backend.task;

import com.community.backend.mapper.NoticeMapper;
import com.community.backend.pojo.Notice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 自定义定时任务，公告
 */
@Component
@Slf4j
public class NoticeTask {

    private final NoticeMapper noticeMapper;

    public NoticeTask(NoticeMapper noticeMapper) {
        this.noticeMapper = noticeMapper;
    }
    /**
     * 定时任务，将过期的公告置为已过期
     */
    @Scheduled(cron = "0 0 10,14,16 * * ? ")
//每天10点，14点，16点执行
    public void updateExpiredNotice() {
        log.info("【定时任务】开始将过期公告置为已过期");
        final int limit = 500;          // 单批条数
        long lastMaxId = 0L;            // 游标
        int total = 0;

        while (true) {
            List<Long> ids = noticeMapper.selectExpiredIds(LocalDateTime.now(), lastMaxId, limit);
            if (ids.isEmpty()) {
                break;
            }
            noticeMapper.updateStatusByIds(ids);
            total += ids.size();
            // 推进游标
            lastMaxId = ids.get(ids.size() - 1);
        }
        log.info("【定时任务】已将 {} 条公告置为已过期", total);
    }

}
